/*
export default {
  async fetch(request, env, ctx) {
    const html = contents => `
    <!DOCTYPE html>
    <html>
      <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width,initial-scale=1">
        <title>测试KV</title>
      </head>

      <body>
        <div class="res">

        </div>
      </body>

      <script>
        window.contents = ${contents}
        const div=document.querySelector('.res')
        div.innerHTML=contents;
        fetch('https://www.imemos.us.kg').then(res=>res.json()).then(data=>{
          document.write(JSON.stringify(data))
        })

      </script>
    </html>
    `

    const kv = KV.getNamespace('TESTDB');
    const setCache = async (key, data) => env.TESTDB.put(key, data)
    const getCache =async (key) =>  env.TESTDB.get(key)


    // await setCache('key','111222')
    // 写入数据
    // let ip1=await env.tvip.get('ip1')
    // let ip2=await env.tvip.get('ip2')
    // let tvlist = await env.tvip.get('tvlist');
    // let cmlist = await env.tvip.get('cmcc');
    let data =await getCache('key');
    // tvlist=tvlist.replaceAll('iptv1',ip1)
    // tvlist=tvlist.replaceAll('iptv2',ip2)
    const page_content = html(data)
    return new Response(page_content, {
      headers: { 'Content-Type': 'text/html' },
    })


},
};

*/
const englishdata={data:[]}
/*
const html=englishdata=>`
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>文件上传与读取</title>

  </head>
  <body>

    <!-- <input type="file" id="fileInput">
    <button onclick="readFile()">读取文件</button>
    -->
    <pre id="fileContent"></pre>
    <script>
    window.ddata=${englishdata};
    const fileInput = document.getElementById('fileInput');
    const fileContent = document.getElementById('fileContent');
    fileContent.textContent=JSON.stringify(ddata);
      function readFile() {

        if (fileInput.files.length === 0) {
          alert('请先选择一个文件！');
          return;
        }
        const file = fileInput.files[0];
        const reader = new FileReader();
        reader.onload = function(event) {
          let textContent = event.target.result;
          let lines=textContent.trim().split('\\n');
          let total=lines.length;
          let data=[]
          for(let i=0;i<total;i++){
            let line=lines[i];
            if(line.length==0)continue;
            let [id,english,chinese]=line.split('|');
            try{
            english=english.replaceAll('”','"')}catch(err){
              console.log(id,english)
            }
            let obj={'id':id,'english':english,'chinese':chinese};
            data.push(obj)
          }
          fetch('/',{method:'PUT',body:JSON.stringify(data)});
          let randomid=~~(Math.random()*total+1);
          fileContent.textContent=JSON.stringify(data[randomid]);
        };
        reader.onerror = function(error) {
          console.error('文件读取失败:', error);
          alert('文件读取失败，请检查文件类型和大小是否支持。');
        };
        reader.readAsText(file);
      }
    </script>
  </body>
</html>
`
*/
const index_html=`
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>KV存取测试</title>
  </head>
  <body>
  <button id="mybtn">下一条</button>
  <pre id="res"></pre>

  <script>
      const res=document.querySelector('#res');
      mybtn.onclick=()=>{
        showinfo()
    }
    showinfo()
    function showinfo(){
      let randomid=~~(Math.random()*3748+1);
      fetch('/getdata?'+randomid).then(res=>res.json()).then(data=>{
        let id=Object.keys(data)[0]
        let e=data[id]['english']
        let c=data[id]['chinese']
        let contents=JSON.stringify(data,null,'\\t')
        res.textContent=e+'\\n'+c
      }) 
    }
  </script>
  </body>
</html>
`

const setCache = async (key, data) => TESTDB.put(key, data)
const getCache =async (key) =>  TESTDB.get(key)
addEventListener('fetch', event => {
  event.respondWith(handleRequest(event.request))
})

async function handleRequest(request) {
  const url = new URL(request.url)
  const pathname = url.pathname
  if (pathname === '/') {
    if(request.method=='PUT'){
      // let body = await request.text();
      // JSON.parse(body)
      // await setCache('english', body)
      // console.log('ok..')
      return new Response('body', { status: 200 })
    }else{
      // let contents=await getCache('english');
      // englishdata.data=JSON.parse(contents)
      // let total=englishdata.data.length;
      // let randomid=~~(Math.random()*total+1);
      // let dd=englishdata.data[randomid]
      // let html=html(JSON.stringify(dd))
     return new Response(index_html, {
      status: 200,
      statusText: 'OK',
      headers: { 'Content-Type': 'text/html' },
    })     
    }

  } else if (pathname === '/getdata') {
    let data=await TESTDB.get('english',{type:'json'})
    let index=request.url;
    let id;
    if(index.includes('?')){
      id=index.split('?')[1]
    }
    let cont=data
    if(id) {
      console.log(id)
      let o={}
      o[id]=data[id]
    cont=o
    }   
    // let data=await getCache('english')
    // let cont=JSON.parse(data)
    // if(Array.isArray(cont)){
    //   let obj={}
    //   for(let i=0;i<cont.length;i++){
    //     let d=cont[i]
    //     obj[d.id]={'english':d.english,'chinese':d.chinese}
    //   }
    //   await setCache('english',JSON.stringify(obj))
    // }
    // data=await getCache('english')
    // cont=JSON.parse(data)
    return Response.json(cont)
  } else if (pathname === '/contact') {
    return new Response('Contact information here.', {
      status: 200,
      statusText: 'OK',
      headers: { 'Content-Type': 'text/plain' },
    })
  } else {
    return new Response('Not Found', {
      status: 404,
      statusText: 'Not Found',
      headers: { 'Content-Type': 'text/plain' },
    })
  }
}